/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.nageoffer.shortlink.project.initialize;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

import static com.nageoffer.shortlink.project.common.constant.RedisKeyConstant.SHORT_LINK_STATS_STREAM_GROUP_KEY;
import static com.nageoffer.shortlink.project.common.constant.RedisKeyConstant.SHORT_LINK_STATS_STREAM_TOPIC_KEY;

/**
 * 初始化短链接监控消息队列消费者组
 * 公众号：马丁玩编程，回复：加群，添加马哥微信（备注：link）获取项目资料
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ShortLinkStatsStreamInitializeTask implements InitializingBean {

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("开始初始化短链接监控消息队列消费者组");
        // 确保消费者组存在
        createConsumerGroup();
        log.info("短链接监控消息队列消费者组初始化完成");
    }

    /**
     * 创建消费者组
     */
    private void createConsumerGroup() {
        try {
            // 检查Stream是否存在
            Boolean hasKey = stringRedisTemplate.hasKey(SHORT_LINK_STATS_STREAM_TOPIC_KEY);
            log.info("检查Stream是否存在: {}, 结果: {}", SHORT_LINK_STATS_STREAM_TOPIC_KEY, hasKey);

            if (hasKey == null || !hasKey) {
                // Stream不存在，添加初始化消息创建Stream
                log.info("Stream不存在，创建Stream和消费者组");
                Map<String, String> map = new HashMap<>();
                map.put("init", "init");
                stringRedisTemplate.opsForStream().add(SHORT_LINK_STATS_STREAM_TOPIC_KEY, map);
                log.info("已添加初始化消息到Stream");
            }

            // 创建消费者组
            log.info("尝试创建消费者组: {}", SHORT_LINK_STATS_STREAM_GROUP_KEY);
            stringRedisTemplate.opsForStream().createGroup(SHORT_LINK_STATS_STREAM_TOPIC_KEY, SHORT_LINK_STATS_STREAM_GROUP_KEY);
            log.info("消费者组创建成功");
        } catch (Exception e) {
            log.error("创建消费者组时发生异常: {}", e.getMessage(), e);
            // 检查是否因为消费者组已存在
            if (e.getMessage() != null && e.getMessage().contains("BUSYGROUP")) {
                log.info("消费者组已存在，无需重复创建");
            } else {
                log.warn("消费者组创建失败，可能影响后续功能");
            }
        }

        // 最后验证一下
        try {
            Boolean hasKey = stringRedisTemplate.hasKey(SHORT_LINK_STATS_STREAM_TOPIC_KEY);
            log.info("最终验证 - Stream是否存在: {}", hasKey);
        } catch (Exception e) {
            log.error("验证Stream时发生异常: {}", e.getMessage());
        }
    }
}